# -*- coding: utf-8 -*-
# @Time    : 2022/10/9 10:23
# @Author  : bitQ
# @Site    : 
# @File    : plane_sim.py
# @Software: PyCharm
from coordinate_conv import *
import math
import json
from threading import Timer
import random
import time
import copy

class SimPos:
    def __init__(self,lat=0,lon=0,alt=0):
        self.lat = lat
        self.lon = lon
        self.alt = alt

class SimPlane:
    def __init__(self, id, pos,speed=0, heading=0):
        self.id = id
        self.pos = pos
        self.speed = speed
        self.heading = heading

    # 生成下一时刻的数据，外部调用
    def next_sec(self):
        rad = math.radians(self.heading)
        y = self.speed * math.sin(rad)
        x = self.speed *math.cos(rad)
        self.pos.lat, self.pos.lon = XYtoGPS(x, y, self.pos.lat, self.pos.lon)
        # print("%d %d %f %f" % (x, y, self.pos.lat, self.pos.lon))

    # 生成json数据
    def gen_json(self):
        data = {'icao':self.id, 'lon':self.pos.lon, 'lat': self.pos.lat, 'alt':self.pos.alt, 'ttrk':self.heading}
        return json.dumps(data)

    # 返回数据列表
    def get_pos(self):
        return [self.id, self.pos.lon, self.pos.lat, self.pos.alt, self.heading]

# 飞机集群模拟
class SimAirline:
    def __init__(self, plane_num, init_pos, track_mode='line'):
        self.plane_num = plane_num
        self.init_pos = init_pos
        self.track_mode = track_mode
        self._next_sec = 1
        self._timer = None
        self._is_running = False
        self.plane_init()

    def plane_init(self):
        self._plane = []
        for i in range(self.plane_num):
            speed = 200 + random.randint(-100, 100)
            heading = random.randint(0,360)
            self._plane.append(SimPlane(i, copy.deepcopy(self.init_pos), speed, heading))

    def start(self):
        self._timer = Timer(self._next_sec, self._task)
        self._timer.start()
        self._is_running = True

    def stop(self):
        self._is_running = False

    def get_json(self):
        li = []
        for i in range(len(self._plane)):
            li.append(self._plane[i].get_pos())

        data = {"timestamp": int(time.time()), "head": ['icao','lon', 'lat', 'alt', 'ttrk'], "data":li}
        return json.dumps(data)

    def _task(self):
        if self._is_running:
            self._timer = Timer(self._next_sec, self._task)
            self._timer.start()
            for p in self._plane:
                p.next_sec()

# if __name__ == '__main__':
#     pos = SimPos(lat=37,lon=121,alt=10000)
#     sim = SimAirline(100, pos)
#     sim.start()
#
#     for i in range(10):
#         time.sleep(1)
#         raw = sim.get_json()
#         print(raw)
#
#     sim.stop()